<?php
namespace App\Http\Controllers\API;

use App\Http\Controllers\Controller;
use App\Http\Requests\AwardCompanyRequest;
use App\Http\Requests\AwardRequest;
use App\Models\Award;
use App\Models\PropositionCompany;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;

class AwardController extends Controller
{
    public function index(Request $request)
    {
        $keyword = $request->get('keyword', '');
        $models = Award::query()->when($keyword , function ($queryString) use ($keyword) {
            return $queryString->where('name', 'like' , '%' .$keyword.'%')
                ->orWhere('code', 'like' , '%'.$keyword.'%');
        })->orderBy('code')->paginate();
        return $models;
    }


    /**
     * 加载赛事
     * @param $modelId
     * @return mixed
     */
    public function show($modelId)
    {
        $award = [];
        $model = $this->findModel($modelId);
        $award['id'] = $model->id;
        $award['code'] = $model->code;
        $award['name'] = $model->name;
        $award['began_at'] = $model->began_at->toDateTimeString();
        $award['ended_at'] = $model->ended_at->toDateTimeString();
        $award['modified_before'] = $model->modified_before->toDateTimeString();
        $award['entryFormTitle'] = $model->entryFormTitle;
        $award['print_text'] = $model->print_text;
        return $award;
    }


    /**
     * 添加一个新赛事
     * @param AwardRequest $request
     * @return array|\Illuminate\Contracts\Routing\ResponseFactory|\Symfony\Component\HttpFoundation\Response
     */
    public function store(AwardRequest $request)
    {
        $model = new Award();
        $model->fill($request->all());
        $model->is_hidden = 0;
        if ($model->save()){
            return ['saveStatus' => 'success'];
        }else{
            return response($model->getErrors()->toArray(), 406);
        }
    }


    /**
     * 更新赛事
     * @param AwardRequest $request
     * @param $modelId
     * @return \Illuminate\Contracts\Routing\ResponseFactory|mixed|\Symfony\Component\HttpFoundation\Response
     */
    public function update(AwardRequest $request, $modelId)
    {
        $model = $this->findModel($modelId);
        $model->fill($request->all());
        if ($model->save()){
            return ['saveStatus' => 'success'];
        }else{
            return response($model->getErrors()->toArray(), 406);
        }
    }


    /**
     * @param $modelId
     * @return mixed
     */
    public function getInfo($modelId)
    {
        return $this->findModel($modelId);
    }

    /**
     * 对应赛事的命题列表
     * @param $awardId
     * @param Request $request
     * @return mixed
     */
    public function getCompanies($awardId, Request $request)
    {
        $keyword = $request->get('keyword', '');
        $model = $this->findModel($awardId);
        return $model->propositionCompanies()->when($keyword , function ($queryString) use ($keyword) {
            return $queryString->where('name', 'like' , '%'.$keyword.'%');
        })->paginate();
    }


    /**
     * 加载指定的赛事命题
     * @param $awardId
     * @param $awardCompanyId
     * @return array
     */
    public function getAwardCompany($awardId, $awardCompanyId)
    {
        $info = [];
        $awardCompany = DB::table('award_company')->find($awardCompanyId);
        $proposition = PropositionCompany::find($awardCompany->company_id);
        $info['id'] = $awardCompany->id;
        $info['name'] = $proposition->name;
        $info['company_id'] = $proposition->id;
        $info['sort'] = $awardCompany->sort;
        $info['type'] = json_decode($awardCompany->type);
        $info['start_at'] = $awardCompany->start_at;
        $info['end_at'] = $awardCompany->end_at;
        $info['modified_before'] =$awardCompany->modified_before;
        $info['works_types'] = DB::table('company_works_type')->where(['award_id' => $awardId, 'company_id' => $awardCompany->company_id])->pluck('works_type_id');
        return $info;
    }


    /**
     * 赛事添加一个命题
     * @param $awardId
     * @param AwardCompanyRequest $request
     * @return array
     */
    public function storeAwardCompany($awardId, AwardCompanyRequest $request)
    {
        $award = $this->findModel($awardId);
        $isUnique = DB::table('award_company')->where(['award_id' => $awardId, 'company_id' => $request->get('company_id')])->first();
        if ($isUnique){
            return response(['is_unique' => '该命题已存在，请勿重复上传'], 422);
        }
        $award->propositionCompanies()->attach($request->get('company_id'), [
            'sort' => $request->get('sort'),
            'start_at' => $request->get('start_at'),
            'end_at' => $request->get('end_at'),
            'modified_before' => $request->get('modified_before'),
            'type' => json_encode($request->get('type'))
        ]);
        $proposition = PropositionCompany::find($request->get('company_id'));
        $proposition->worksTypes()->attach($request->get('works_types'), ['award_id' => $awardId]);
        return ['saveStatus' => 'success', 'name' => $proposition->name];
    }


    /**
     * 赛事更新一个命题
     * @param $awardId
     * @param $awardCompanyId
     * @param AwardCompanyRequest $request
     * @return array
     */
    public function updateAwardCompany($awardId, $awardCompanyId, AwardCompanyRequest $request)
    {
        $awardCompany = DB::table('award_company')->find($awardCompanyId);
        DB::table('award_company')->where('id' , $awardCompanyId)->update([
            'sort' => $request->get('sort'),
            'start_at' => $request->get('start_at'),
            'end_at' => $request->get('end_at'),
            'modified_before' => $request->get('modified_before'),
            'type' => json_encode($request->get('type'))
        ]);
        $proposition = PropositionCompany::find($awardCompany->company_id);
        DB::table('company_works_type')->where(['award_id' => $awardId, 'company_id' => $proposition->id])->delete();
        $proposition->worksTypes()->attach($request->get('works_types'), ['award_id' => $awardId]);
        return ['saveStatus' => 'success'];
    }

    /**
     * 赛事删除一个命题
     * @param $awardId
     * @param $awardCompanyId
     * @return array
     */
    public function deleteAwardCompany($awardId, $awardCompanyId)
    {
        $awardCompany = DB::table('award_company')->find($awardCompanyId);
        DB::table('company_works_type')->where(['award_id' => $awardId, 'company_id' => $awardCompany->id])->delete();
        DB::table('award_company')->where('id' , $awardCompanyId)->delete();
        return ['deleteStatus' => 'success'];
    }


    /**
     * 加载model
     * @param $modelId
     * @return mixed
     */
    public function findModel($modelId)
    {
        $model = Award::find($modelId);
        return $model;
    }
}